package com.yinile.zc03.service;

import java.util.UUID;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.BeanUtils;

import com.yinile.zc03.domain.Book;
import com.yinile.zc03.dao.BookRepository;
import com.yinile.zc03.sys.result.ObjectOkResult;
import com.yinile.zc03.sys.utils.StringUtils;
import com.yinile.zc03.sys.exception.NoRecordException;
import com.yinile.zc03.sys.utils.StringUtils;
import com.yinile.zc03.sys.result.BaseResult;

/**
 * 书的服务类
 */
@Service
public class BookService {
	@Autowired
	BookRepository bookRepository;

	/**
	 * 根据ID查找
	 */
	public ObjectOkResult findOne(String id) {
		if (StringUtils.isEmpty(id)) {
			throw new NoRecordException("缺少ID");
		}
		Book book = this.bookRepository.findOne(id);
		if (book == null) {
			throw new NoRecordException("没有这条记录");
		}
		return new ObjectOkResult(book);
	}

	/**
	 * 根据ID删除
	 */
	@Transactional
	public BaseResult delete(String id) {
		this.bookRepository.delete(id);
		BaseResult br = new BaseResult();
		br.message = "success";
		return br;
	}
	
	/**
	 * 保存
	 */
	@Transactional
	public ObjectOkResult save(Book book) {
		book.setId(UUID.randomUUID().toString());
		this.bookRepository.save(book);
		return new ObjectOkResult(book);
	}
	
	/**
	 * 更新
	 */
	@Transactional
	public ObjectOkResult update(Book book) {
		if (StringUtils.isEmpty(book.getId())) {
			throw new NoRecordException("缺少ID");
		}
		// 从数据库中查找出来的实体
		Book dbBook = this.bookRepository.findOne(book.getId());
		if (dbBook == null) {
			throw new NoRecordException("没有这条记录");
		}
		// TODO 根据业务要求，确定哪些属性可以更新，这里仅仅作为一个例子
		BeanUtils.copyProperties(book, dbBook);
		return new ObjectOkResult(book);
	}
	

}
